<!-- 首次登录, 强制修改密码页 -->
<template>
	<div class="register">
		<el-form ref="userRef" :model="psdForm" :rules="psdFormRules" class="register-form">
			<!-- logo title -->
			<div class="title" v-if="phoneStatus === 'false'">首次登录请绑定手机号并重置密码</div>
			<div class="title" v-else>首次登录请重置密码</div>
			<!-- 账号 -->
			<div class="user mb20">
				<span>账号 :</span>
				&nbsp;
				<span>{{ route.query.userName }}</span>
			</div>
			<!-- 绑定手机号 -->
			<el-form-item prop="phonenumber" class="mb36" v-if="phoneStatus === 'false'">
				<el-input v-model="psdForm.phonenumber" size="large" placeholder="请输入手机号进行绑定" auto-complete="off">
					<template #prefix><svg-icon icon-class="shouji" class="el-input__icon input-icon" /></template>
				</el-input>
			</el-form-item>
			<!-- 手机号验证码 -->
			<el-form-item prop="code" class="mb36" v-if="phoneStatus === 'false'">
				<el-input v-model="psdForm.code" size="large" placeholder="请输入验证码" auto-complete="off" class="codeBtnStyle">
					<template #append>
						<el-button @click="getCode" :loading="sendCodeLoading" :disabled="disabled">{{ sendCodeContent }}</el-button>
					</template>
				</el-input>
			</el-form-item>
			<!-- 新密码 -->
			<el-form-item prop="password" class="mb36">
				<el-input v-model="psdForm.password" type="password" size="large" auto-complete="off" placeholder="请输入新密码" show-password ref="psdRef">
					<template #prefix><svg-icon icon-class="psd" class="el-input__icon input-icon psd" /></template>
				</el-input>
			</el-form-item>
			<!-- 确认新密码 -->
			<el-form-item prop="secondPassword" class="mb36">
				<el-input v-model="psdForm.secondPassword" type="password" size="large" auto-complete="off" placeholder="请确认新密码" show-password @keyup.enter="handleSubmitPwd">
					<template #prefix><svg-icon icon-class="psd" class="el-input__icon input-icon psd" /></template>
				</el-input>
			</el-form-item>
			<!-- 提交按钮 -->
			<el-form-item>
				<el-button :loading="loading" size="large" type="primary" @click.prevent="handleSubmitPwd" class="submit-btn w100">
					<span v-if="!loading">提 交</span>
					<span v-else>提 交 中...</span>
				</el-button>
			</el-form-item>
		</el-form>
	</div>
	<!-- 备案 -->
	<Icp />
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import Icp from '@/components/Icp/index.vue'
import { forceResetPwdAPI, captchaAPI, changeCaptchaAPI } from '@/api/login'
import useUserStore from '@/store/modules/user'
import { ref } from 'vue'
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const psdForm = ref({
	phonenumber: '',
	code: '',
	userId: route.query.userId, // 用户id
	userName: route.query.userName, // 用户名
	password: '', // 第一次密码
	secondPassword: '' // 第二次密码
})
// 数据库中是否存在账号对应的手机号，true：存在，false：不存在，需要用户补充手机号
let phoneStatus = ref(true)
phoneStatus = route.query.phoneStatus

const loading = ref(false) // loading开关
// 两次密码是否一致的校验函数
const equalToPassword = (rule, value, callback) => {
	if (psdForm.value.password !== value) {
		callback(new Error('两次输入的密码不一致'))
	} else {
		callback()
	}
}

// 密码验证规则
const psdFormRules = {
	phonenumber: [
		{ required: true, message: '请输入手机号', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
	],
	code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
	password: [
		{ required: true, trigger: 'blur', message: '请输入新密码' },
		{ pattern: /^[a-zA-Z0-9!@#$%^&*]+$/, message: '密码只能输入数字，字母，特殊符号', trigger: 'blur' },
		{ min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' }
	],
	secondPassword: [
		{ required: true, trigger: 'blur', message: '请确认新密码' },
		{ min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' },
		{ pattern: /^[a-zA-Z0-9!@#$%^&*]+$/, message: '密码只能输入数字，字母，特殊符号', trigger: 'blur' },
		{ required: true, validator: equalToPassword, trigger: 'blur' }
	]
}

const sendCodeContent = ref('获取验证码')
const sendCodeLoading = ref(false)
const disabled = ref(false)
// 获取验证码
function getCode() {
	proxy.$refs.userRef.validateField('phonenumber', (valid) => {
		if (!valid) return false
		sendCodeLoading.value = true
		captchaAPI({ phoneNumber: psdForm.value.phonenumber })
			.then((res) => {
				sendCodeLoading.value = false
				disabled.value = true
				startCountdown()
			})
			.catch((err) => {
				sendCodeLoading.value = false
			})
	})
}
// 60s倒计时
const startCountdown = () => {
	let seconds = 60
	const timer = setInterval(function () {
		seconds--
		if (seconds > 0) {
			sendCodeContent.value = `发送验证码(${seconds})`
		} else {
			clearInterval(timer)
			sendCodeContent.value = '发送验证码'
			disabled.value = false
		}
	}, 1000)
}

// 提交新密码
function handleSubmitPwd() {
	proxy.$refs.userRef.validate((valid) => {
		if (valid) {
			loading.value = true
			const params = {
				secondPassword: psdForm.value.secondPassword
			}
			const data = {
				userName: psdForm.value.userName,
				userId: psdForm.value.userId,
				password: psdForm.value.password
			}
			if (psdForm.value.phonenumber) {
				data.phonenumber = psdForm.value.phonenumber
			}
			const validationPromise = new Promise((resolve, reject) => {
				if (psdForm.value.code) {
					data.code = psdForm.value.code
					// 校验验证码
					changeCaptchaAPI({
						phoneNumber: psdForm.value.phonenumber,
						code: psdForm.value.code
					})
						.then((res) => {
							if (res.code != 200) {
								proxy.$modal.msgError(res.msg)
								reject() // 如果验证失败，则reject
							} else {
								loading.value = true
								resolve(true) // 如果验证通过，则resolve
							}
						})
						.catch((err) => {
							loading.value = false
							reject(err) // 异常情况下也reject
						})
				} else {
					// 如果没有验证码，直接resolve为true
					resolve(true)
				}
			})
			validationPromise
				.then((isValid) => {
					if (isValid) {
						const token = localStorage.getItem('firstLogin')
						forceResetPwdAPI(params, data, token)
							.then(() => {
								loading.value = false
								ElMessageBox.alert('修改密码成功!', '提示', {
									confirmButtonText: '确定',
									type: 'success',
									'show-close': false
								}).then(() => {
									// 点击确定按钮直接登录
									useUserStore()
										.login({ username: data.userName, password: data.password })
										.then(() => {
											router.push({ path: '/' })
										})
								})
							})
							.catch(() => {
								loading.value = false
							})
					}
				})
				.catch(() => {
					// 处理验证失败的情况
				})
		}
	})
}

// 输入密码获取焦点
onMounted(() => {
	if (!psdForm.value.password) {
		proxy.$refs.psdRef.focus()
	}
})
// 清除用户首次登录的token
onBeforeUnmount(() => {
	localStorage.removeItem('firstLogin')
})
</script>

<style lang="scss" scoped>
.register {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-image: url('https://glm-1324073348.cos.ap-nanjing.myqcloud.com/2024/10/18/fa076049315040fd86a62760486af3071729231799530.png');
	background-size: 100% 100%;
}
.title {
	color: #fff;
	font-size: 24px;
	text-align: center;
	margin-bottom: 30px;
}
.user {
	display: flex;
	align-items: center;
	color: #fff;
	span:first-child {
		font-weight: bold;
	}
}
.register-form {
	border-radius: 6px;
	width: 420px;
	padding: 25px 25px 5px 25px;
	background-color: transparent;
	.el-input {
		height: 40px;
		input {
			height: 40px;
		}
	}
	.input-icon {
		height: 40px;
		width: 16px;
		margin-left: 0px;
	}
}
// 输入框文字
:deep(.el-input__inner) {
	color: #fff !important;
}
// 输入框背景色
:deep(.el-input__wrapper) {
	background-color: rgb(255, 255, 255, 0.01);
}
// 输入框的placeholder
:deep(.el-input__inner::placeholder) {
	color: #fff;
}
// 密码眼睛
:deep(.el-input__password) {
	font-size: 20px;
	color: #fff;
}
.mb36 {
	margin-bottom: 36px;
}
.codeBtnStyle :deep(.el-input-group__append, .el-input-group__prepend) {
	background: #409eff;
	color: #fff;
}

// input在浏览中自动填充后的默认样式 input:-internal-autofill-selected
::v-deep(input:-webkit-autofill) {
	-webkit-box-shadow: 0 0 0 0px transparent inset !important;
}
::v-deep(input:-internal-autofill-previewed, input:-internal-autofill-selected) {
	-webkit-text-fill-color: #ffffff !important;
	transition: background-color 5000s ease-in-out 0s !important;
}
::v-deep(input:-internal-autofill-selected) {
	transition: background-color 5000s ease-in-out 0s !important;
	background-color: transparent !important;
	-webkit-text-fill-color: #fff !important;
}
</style>
